package com.dm.cloud.core.config.rest;


import cn.hutool.core.util.StrUtil;
import com.dm.cloud.core.config.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author sg
 * @ClassName CustomClientHttpRequestInterceptor.java
 * @Description 自定义拦截器，封装RestTemplate，写入请求头信息
 * @Date 2021/08/18 14:08
 */
@Slf4j
@Component
public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    @Autowired
    private HttpServletRequest request;
    /**
     * header中的自定义头，用与前端发送过来的网关头
     */
    @Override
    public ClientHttpResponse intercept(
            HttpRequest request, byte[] body,
            ClientHttpRequestExecution execution) throws IOException {
        try {
            log.debug("http {} request {} with header {}", request.getMethod(), request.getURI(), request.getHeaders());
            if(this.request !=null ){
                if(StrUtil.isNotEmpty(this.request.getHeader(CommonConstants.AUTH_HEAD_KEY))){
                    request.getHeaders().set(CommonConstants.AUTH_HEAD_KEY, String.valueOf(this.request.getHeader(CommonConstants.AUTH_HEAD_KEY)));
                }
            }
            request.getHeaders().set(HttpHeaders.ACCEPT_CHARSET, "UTF-8");
        }catch (Exception e){
            log.debug("none request error");
        }
        return execution.execute(request, body);
    }
}